package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.UserDto;
import com.zzyl.entity.User;
import com.zzyl.entity.UserRole;
import com.zzyl.mapper.*;
import com.zzyl.properties.SecurityConfigProperties;
import com.zzyl.service.RoleService;
import com.zzyl.service.UserRoleService;
import com.zzyl.service.UserService;
import com.zzyl.utils.EmptyUtil;
import com.zzyl.utils.NoProcessing;
import com.zzyl.vo.RoleVo;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleService roleService;
    @Autowired
    private PostMapper postMapper;
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserRoleService userRoleService;

    @Override
    public PageResponse<UserVo> findUserPage(UserDto userDto, int pageNum, int pageSize) {

        if (!EmptyUtil.isNullOrEmpty(userDto.getDeptNo())){
            userDto.setDeptNo(NoProcessing.processString(userDto.getDeptNo()));
        }

        PageHelper.startPage(pageNum, pageSize);
        Page<List<UserVo>> page = userMapper.selectList(userDto);
        PageResponse<UserVo> pageResponse = PageResponse.of(page, UserVo.class);


        if (!EmptyUtil.isNullOrEmpty(pageResponse.getRecords())){
            List<Long> userIds = pageResponse.getRecords().stream().map(UserVo::getId).collect(Collectors.toList());
            //查询对应角色
            List<RoleVo> roleVoList = roleService.findRoleVoListInUserId(userIds);

            //装配数据
            pageResponse.getRecords().forEach(n->{
                n.setDeptName(deptMapper.findDeptByDeptNo(n.getDeptNo()));
                n.setPostName(postMapper.findPostByPostNo(n.getPostNo()));

                //装配角色
                Set<String> roleVoIds = Sets.newHashSet();
                //
                Set<String> roleVoLabels = Sets.newHashSet();
                roleVoList.forEach(r->{
                    if (String.valueOf(n.getId()).equals(r.getUserId())){
                        roleVoIds.add(String.valueOf(r.getId()));
                        roleVoLabels.add(r.getRoleName());

                    }
                });
                n.setRoleLabels(roleVoLabels);
                n.setRoleVoIds(roleVoIds);
            });
        }

        return pageResponse;

    }


    @Autowired
    private SecurityConfigProperties securityConfigProperties;

    @Override
    public UserVo createUser(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getEmail());
        user.setDeptNo(userDto.getDeptNo());
        user.setPostNo(userDto.getPostNo());
        user.setRealName(userDto.getRealName());
        user.setMobile(userDto.getMobile());
        user.setSex(userDto.getSex());
        user.setDataState(userDto.getDataState());
        user.setPassword(BCrypt.hashpw(securityConfigProperties.getDefaulePassword(), BCrypt.gensalt()));
        user.setEmail(userDto.getEmail());
        user.setNickName(userDto.getRealName());

        userMapper.insert(user);
        UserVo userVo = new UserVo();
        List<UserRole> userRoleList = new ArrayList<>();
        userDto.getRoleVoIds().forEach(n->{
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(Long.valueOf(n));
            userRole.setDataState(userDto.getDataState());
            userRoleList.add(userRole);
        });
        userRoleMapper.batchInsert(userRoleList);



        return null;
    }

    @Override
    public Boolean resetPasswords(String userId) {
        String password = BCrypt.hashpw(securityConfigProperties.getDefaulePassword(), BCrypt.gensalt());
        User user = User.builder().password(password).build();
        user.setId(Long.valueOf(userId));
        int flag = userMapper.updateByPrimaryKeySelective(user);
        if (flag>0){
            return true;
        }
        return false;
    }

    @Override
    public Boolean updateUser(UserDto userDto) {
        User user = BeanUtil.toBean(userDto, User.class);
        int flag = userMapper.updateByPrimaryKeySelective(user);
        if (flag==0){
            throw new RuntimeException("更新用户失败");
        }

        if (!EmptyUtil.isNullOrEmpty(userDto.getRoleVoIds())){
            //删除用户角色关系
            boolean flag1 = userRoleService.daleteUserRoleByUserId(userDto.getId());
            if (!flag1){
                throw new RuntimeException("删除用户角色关系失败");
            }

            //重新保存角色中间表
            List<UserRole> userRoles = Lists.newArrayList();
            userDto.getRoleVoIds().forEach(r->{
                userRoles.add(UserRole.builder()
                        .userId(user.getId())
                        .roleId(Long.valueOf(r))
                        .dataState(SuperConstant.DATA_STATE_0)
                        .build());
            });
            flag = userRoleService.batchInsert(userRoles);
            if (flag==0){
                throw new RuntimeException("保存角色中间表出错");
            }
        }
        return true;

    }

    @Override
    public List<UserVo> findUserList(UserVo userVo) {
        if (!EmptyUtil.isNullOrEmpty(userVo.getDeptNo())){
            userVo.setDeptNo(NoProcessing.processString(userVo.getDeptNo()));
        }
        List<User> userList = userMapper.selectList1(userVo);
        List<UserVo> userVoList = BeanUtil.copyToList(userList, UserVo.class);
        if (!EmptyUtil.isNullOrEmpty(userVoList)){
            List<Long> userIdSet = userVoList.stream().map(UserVo::getId).collect(Collectors.toList());
            //查询对应角色
            List<RoleVo> roleVoList = roleService.findRoleVoListInUserId(userIdSet);
            //装配数据
            userVoList.forEach(n->{
                //装配角色
                Set<String> roleVoIds = Sets.newHashSet();
                roleVoList.forEach(r->{
                    if (String.valueOf(n.getId()).equals(r.getUserId())){
                        roleVoIds.add(String.valueOf(r.getId()));
                    }
                });
                n.setRoleVoIds(roleVoIds);

            });
        }
        return userVoList;
    }

    @Override
    public Boolean updateUserStatus(String id, Integer status) {
       Boolean flag = userMapper.updateStatuById(id,status);
       return flag;
    }

    @Override
    public int deleteUserByIds(List<Long> userIds) {
        // 删除用户与角色关联
        userRoleService.deleteUserRoleInUserId(userIds);
        // 删除用户与岗位关联
        return userMapper.deleteUserByIds(userIds);
    }


}
